import { PageContainer, ProTable } from "@ant-design/pro-components";
import { history } from "@@/exports";
import { useEffect, useRef, useState } from "react";
import { Button, Dropdown, Popconfirm, Space, message } from "antd";
import { calcColumns, namespace } from "@/pages/course/info/index/configFile";
import { connect } from "umi";
import Https from "@/utils/Https";
import { DownOutlined } from "@ant-design/icons";
import styles from "./index.less";
import RuleClass from "./rule";
import { useLocation } from "umi";
const Page = (props) => {
  const { dispatch } = props;
  const stateParams = useLocation().state;
  const actionRef = useRef();
  //课程类型( 1私教课、2团课、3班课)
  const [key, setKey] = useState("1");
  const [courseCoachList, setCourseCoachList] = useState({});
  const [open, setOpen] = useState("");
  const [courseInfo, setCourseInfo] = useState({});
  //删除课程
  const deleteCourse = async (id) => {
    let res = await Https.post(`/course/logicDeleteInfo/${id}`, {}, true);
    console.log(res, "_res");
    if (res.code == 200) {
      message.success("删除成功");
      actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };
  //上下架
  const toggleState = (params) => {
    dispatch({
      type: `${namespace}/updateInfoStatus`,
      params,
      callback: (res) => {
        actionRef.current?.reload();
      },
    });
  };
  // //获取场馆列表
  // const getAllVenue = async () => {
  //   let res: any = await Https.post("/course/venueAllList", {}, true);
  //   if (res.code == 200 && res.data) {
  //     let objList = {};
  //     if (res.data && res.data.length > 0) {
  //       res.data.map(
  //         (v) =>
  //           (objList[v.id] = {
  //             text: v.venueName,
  //           })
  //       );
  //       setVenueList(objList);
  //     }
  //   }
  // };
  //获取教练列表
  const getCourseCoach = async () => {
    let res: any = await Https.get("/employee/manage/allCoachList", {}, true);
    if (res.code == 200 && res.data) {
      let objList = {};
      if (res.data && res.data.length > 0) {
        res.data.map(
          (v) =>
            (objList[v.userId] = {
              text: v.nickName,
            })
        );
        setCourseCoachList(objList);
      }
    }
  };
  //操作按钮
  const operate = [
    {
      title: "操作",
      fixed: "right",
      dataIndex: "actions",
      align: "center",
      hideInSearch: true,
      render: (_, record) => {
        const { id, courseStatus, courseType } = record;
        const _status = parseInt(courseStatus, 10);
        return (
          <Space>
            <Button
              style={{ padding: 0 }}
              type="link"
              onClick={() => history.push(`/course/edit/${key}/${record.id}`)}
            >
              编辑
            </Button>
            {record.courseStatus != "2" && (
              <Button
                style={{ padding: 0 }}
                type="link"
                onClick={() =>
                  history.push(
                    `/course/details/${record.courseType}/${record.id}/${record.courseStatus}`
                  )
                }
              >
                详情
              </Button>
            )}
            <Dropdown
              arrow
              menu={[]}
              dropdownRender={(menu) => (
                <div className={styles.dorpDownBox}>
                  {courseType != "1" && (
                    <div className={styles.dorpDownItem}>
                      <Button
                        style={{ padding: 0 }}
                        type="link"
                        onClick={() => {
                          setOpen("rule");
                          setCourseInfo({
                            id: record.id,
                            appointRule: record.appointRule,
                          });
                        }}
                      >
                        预约规则
                      </Button>
                    </div>
                  )}
                  <div className={styles.dorpDownItem}>
                    {_status === 0 ? (
                      <Popconfirm
                        title="确定下架该课程吗？"
                        onConfirm={() => toggleState({ id, courseStatus: 1 })}
                      >
                        <Button style={{ padding: 0 }} type="link" danger>
                          下架
                        </Button>
                      </Popconfirm>
                    ) : (
                      <Button
                        style={{ padding: 0 }}
                        type="link"
                        onClick={() => toggleState({ id, courseStatus: 0 })}
                      >
                        上架
                      </Button>
                    )}
                  </div>
                  <div className={styles.dorpDownItem}>
                    <Popconfirm
                      title="确定删除该课程吗？"
                      onConfirm={() => {
                        deleteCourse(record.id);
                      }}
                    >
                      <Button style={{ padding: 0 }} type="link" danger>
                        删除
                      </Button>
                    </Popconfirm>
                  </div>
                </div>
              )}
            >
              <a
                onClick={(e) => {
                  e.preventDefault();
                }}
              >
                <Space>
                  更多
                  <DownOutlined />
                </Space>
              </a>
            </Dropdown>
          </Space>
        );
      },
    },
  ];
  useEffect(() => {
    getCourseCoach();
  }, []);
  useEffect(() => {
    if (stateParams) {
      setKey(stateParams.courseType);
    }
  }, [stateParams]);
  return (
    <PageContainer
      title="课程信息管理"
      tabList={[
        {
          tab: "团课",
          key: "2",
        },
        {
          tab: "私教课",
          key: "1",
        },
        {
          tab: "班课",
          key: "3",
        },
      ]}
      tabActiveKey={key}
      onTabChange={(e) => {
        setKey(e);
        actionRef.current && actionRef.current.reset();
        actionRef.current && actionRef.current.reload();
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: 1500 }}
        toolBarRender={() => [
          <>
            <Button
              onClick={() => {
                if (key == "1") {
                  history.push("/course/personal");
                } else if (key == "2") {
                  history.push("/course/schedule");
                }
              }}
            >
              去排课
            </Button>
            <Button
              type="primary"
              key="add"
              onClick={() => history.push(`/course/add/${key}`)}
            >
              新建课程
            </Button>
          </>,
        ]}
        request={async (query) => {
          return await dispatch({
            type: `${namespace}/getClassList`,
            params: {
              ...query,
              courseType: key,
            },
          });
        }}
        pagination={{
          showSizeChanger: true,
        }}
        columns={calcColumns({
          operate,
          courseType: key,
          courseCoachList,
        })}
      />
      <RuleClass
        open={open == "rule"}
        courseInfo={courseInfo}
        onClose={() => {
          setOpen("");
        }}
        onSuccess={() => {
          setOpen("");
          actionRef.current && actionRef.current.reload();
        }}
      />
    </PageContainer>
  );
};

export default connect((state) => {
  return {
    ...state[namespace],
    submitLoading: state.loading.effects[`${namespace}/submitItem`],
  };
})(Page);
